<template>
  <div class="p-2">
    <el-card shadow="never" v-loading="loading">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-semibold">考试记录详情</span>
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        </div>
      </template>

      <!-- 考试基本信息 -->
      <div class="mb-6">
        <h3 class="text-base font-medium mb-4 text-gray-700">考试基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">考试标题：</span>
              <span class="value">{{ examDetail.examTitle }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">考生姓名：</span>
              <span class="value">{{ examDetail.nickName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">考试状态：</span>
              <dict-tag :options="ai_answer_record_status" :value="examDetail.status" />
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-4">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ parseTime(examDetail.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">提交时间：</span>
              <span class="value">{{ parseTime(examDetail.submitTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">考试时长：</span>
              <span class="value">{{ examDetail.duration }} 分钟</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 成绩统计 -->
      <div class="mb-6">
        <h3 class="text-base font-medium mb-4 text-gray-700">成绩统计</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总分" :value="examDetail.totalScore" suffix="分" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="得分" :value="examDetail.score" suffix="分" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="正确率" :value="correctRate" suffix="%" :precision="1" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="及格分" :value="examDetail.passScore" suffix="分" />
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-4">
          <el-col :span="6">
            <el-statistic title="题目总数" :value="examDetail.totalQuestions" suffix="题" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="答对题数" :value="examDetail.correctCount" suffix="题" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="总用时" :value="examDetail.totalTime" suffix="分钟" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="最大用时" :value="examDetail.maxTime" suffix="分钟" />
          </el-col>
        </el-row>
      </div>

      <!-- 答题详情 -->
      <div class="mb-6">
        <h3 class="text-base font-medium mb-4 text-gray-700">答题详情</h3>
        <el-table :data="answerList" border stripe>
          <el-table-column label="题号" align="center" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="题目内容" prop="questionTitle" min-width="300">
            <template #default="scope">
              <ContentRenderer :content="scope.row.questionTitle" />
            </template>
          </el-table-column>
          <el-table-column label="题目类型" align="center" width="120">
            <template #default="scope">
              <dict-tag :options="ai_question_type" :value="scope.row.questionType" />
            </template>
          </el-table-column>
          <el-table-column label="用户答案" prop="answerContent" width="200" />
          <el-table-column label="正确答案" prop="correctAnswer" width="200" />
          <el-table-column label="是否正确" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isCorrect ? 'success' : 'danger'">
                {{ scope.row.isCorrect ? '正确' : '错误' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="得分" align="center" width="80">
            <template #default="scope">
              {{ scope.row.scoreEarned }}
            </template>
          </el-table-column>
          <el-table-column label="用时" align="center" width="100">
            <template #default="scope">
              {{ scope.row.stayTime }}秒
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup name="UserExamDetail" lang="ts">
import { getUserExams } from '@/api/answer/userExams';
import { listUserAnswersByUserExamId } from '@/api/answer/userAnswers';
import { UserExamsVO } from '@/api/answer/userExams/types';
import { UserAnswersVO } from '@/api/answer/userAnswers/types';
import ContentRenderer from '@/components/ContentRenderer/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ai_answer_record_status, ai_question_type } = toRefs<any>(proxy?.useDict('ai_answer_record_status', 'ai_question_type'));
const route = useRoute();
const router = useRouter();

const loading = ref(true);
const examDetail = ref<UserExamsVO>({});
const answerList = ref<UserAnswersVO[]>([]);

// 计算正确率
const correctRate = computed(() => {
  if (!examDetail.value.totalQuestions || examDetail.value.totalQuestions === 0) {
    return 0;
  }
  return (examDetail.value.correctCount / examDetail.value.totalQuestions) * 100;
});

/** 获取考试记录详情 */
const getExamDetail = async () => {
  try {
    loading.value = true;
    const userExamId = route.params.userExamId as string;
    
    // 获取考试记录基本信息
    const examRes = await getUserExams(userExamId);
    examDetail.value = examRes.data;
    
    // 获取答题记录
    const answerRes = await listUserAnswersByUserExamId({
      userExamId: Number(userExamId),
      pageNum: 1,
      pageSize: 1000
    });
    
    // 处理答题记录，添加题目信息
    answerList.value = answerRes.rows.map(answer => ({
      ...answer,
      questionTitle: answer.questionTitle || '题目内容',
      correctAnswer: answer.correctAnswer || '正确答案'
    }));
    
  } catch (error) {
    proxy?.$modal.msgError('获取考试详情失败');
  } finally {
    loading.value = false;
  }
};

/** 返回列表页 */
const goBack = () => {
  router.push('/answer/userExams');
};

onMounted(() => {
  getExamDetail();
});
</script>

<style scoped>
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
}

:deep(.el-statistic__content) {
  font-size: 24px;
}

:deep(.el-statistic__title) {
  font-size: 14px;
  color: #909399;
}
</style>